import os
from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import smtplib
from email.utils import formataddr
from email.utils import parseaddr
from email.header import Header


def format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


def main():
    print('hello')

    print(os.path)

    from_addr = '137740537@qq.com'
    password = 'etfvyhujnipl.'

    to_addr = '306800850@qq.com'

    smtp_server = 'smtp.qq.com'
    smtp_port = 465
    smtp_port = 587

    # plain 邮件
    # msg = MIMEText('hello, It\'s a test ^_^', 'plain', 'utf-8')
    # html 邮件
    # msg = MIMEText('<html><body><h1>Hello</h1>' +
    #                '<p>send by <a href="http://www.python.org">Python</a>...</p>' +
    #                '</body></html>', 'html', 'utf-8')
    # multipart
    msg = MIMEMultipart()
    text = MIMEText('<html><body><h1>Hello</h1>' +
                    '<p>send by <a href="http://www.python.org">Python</a>...</p>' +
                    '</body></html>', 'html', 'utf-8')
    msg['From'] = format_addr('From <%s>' % from_addr)
    msg['To'] = format_addr('To <%s>' % to_addr)
    msg['Subject'] = Header('hello subject', 'utf-8').encode()
    msg.attach(text)
    file_jpg_name = 'test.jpg'
    with open(file_jpg_name, 'rb') as file_jpg:
        print(file_jpg.name)
        print(os.path.splitext(file_jpg.name))
        # 设置附件的MIME和文件名，这里是png类型:
        mime = MIMEBase('image', 'png', filename=file_jpg.name)
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename='test.png')
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(file_jpg.read())
        # 用Base64编码:
        encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)
    print('init server')
    server = smtplib.SMTP(smtp_server, smtp_port)
    # server = smtplib.SMTP_SSL(smtp_server, smtp_port)
    server.ehlo()
    server.starttls()
    print('set_debuglevel')
    server.set_debuglevel(1)
    print('login')
    server.login(from_addr, 'jcxpvvzhpujncbca')
    print('send mail')
    server.sendmail(from_addr, [to_addr], msg.as_string())
    print('quit')
    server.quit()


if __name__ == '__main__':
    main()
